package framework.action;

import framework.config.ActionConfig;
import framework.config.ForwardConfig;
import framework.config.ModuleConfig;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ActionServlet extends HttpServlet {
    private ModuleConfig moduleConfig;

    private Map<String,Object> actions=new HashMap<String,Object>();

    private String configPath;

    @Override
    public void init() throws ServletException {

        configPath=getInitParameter("config");

        //解析配置文件
        Digester digester= DigesterLoader.createDigester(ActionServlet.class
                                                                      .getClassLoader()
                                                                      .getResource("framework/config/rule.xml"));


        moduleConfig=new ModuleConfig();
        digester.push(moduleConfig);

        //这个框架的配置文件叫做mvc.xml方法src下
        try {
            digester.parse(ActionServlet.class
                                        .getClassLoader()
                                        .getResourceAsStream(configPath));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException("解析mvc配置文件失败",e);
        }

    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //解析请求
        String path=request.getServletPath();


        //将请求扩展名截掉
        path=path.substring(0,path.lastIndexOf("."));

        System.out.println("path = " + path);


        //根据请求查找配置 ActionConfig
        ActionConfig actionConfig=moduleConfig.findAction(path);

        System.out.println("actionConfig = " + actionConfig);

        //当请求不存在（没有配置这个请求）时
        if(actionConfig==null){
            response.sendError(HttpServletResponse.SC_NOT_FOUND,path+"不存在");
            return;
        }


        //根据ActionConfig配置中的type和method调用对应的方法，返回字符串result
        try {
            Class actionClass=Class.forName(actionConfig.getType());

            //创建Action对象，做成单例
            Object action=actions.get(actionConfig.getType());
            if(action==null){
                action=actionClass.newInstance();
                actions.put(actionConfig.getType(),action);
            }



            Method method=actionClass.getMethod(actionConfig.getMethod(),HttpServletRequest.class,HttpServletResponse.class);

            String result= (String) method.invoke(action,request,response);


            if(result==null){
                return;
            }


            //根据result查找ForwardConfig的配置
            ForwardConfig forwardConfig=actionConfig.findForward(result);


            //如果Action中返回的字符串在配置文件中不存在(没有做forward的配置)
            if(forwardConfig==null){
                response.sendError(HttpServletResponse.SC_NOT_FOUND,result+"没有配置");
                return;
            }



            //根据配置转发或重定向到ForwardConfig中的path
            if(forwardConfig.isRedirect()){
                //重定向到path
                response.sendRedirect(request.getContextPath()+forwardConfig.getPath());
            }else{
                //转发到path
                request.getRequestDispatcher(forwardConfig.getPath()).forward(request,response);
            }














        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }


    }
}
